package guestbook;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null && req.getParameter("logout") != null) {
            resp.sendRedirect(userService.createLogoutURL("/"));

        } else if (user != null) {
            resp.setContentType("text/html");
            resp.getWriter()
                    .println(
                            "<html><body>"
                                    + "Hello, "
                                    + user.getNickname()
                                    + "<br />"
                                    + "<a href='guestbook?logout=true'>Logout</a>"
                                    + "<hr />"
                                    + "<img src='http://code.google.com/appengine/images/appengine-noborder-120x30.gif' alt='Powered by Google App Engine' />"
                                    + "</body></html>");

        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
    }

}
